#coding=utf-8
import json,requests,base64,getpass,pymysql
import time as _time
from time import sleep
from datetime import datetime
from io import BytesIO
from PIL import Image
from sys import version_info
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement

def webdriver_init():
    chrome_options = webdriver.ChromeOptions()
    # chrome_options.add_argument("--proxy-server=http://218.75.158.153:3128")  # 代理ip
    chrome_options.add_argument('--headless')   # 增加无界面选项
    chrome_options.add_argument('log-level=3')
    chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
    chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口大小, 窗口大小会有影响
    u=webdriver.Chrome(options=chrome_options,executable_path="./chromedriver")
    return u
    
def login(un,pd,school):
    headers = {'host':'swxykdsx.chuangnengkeji.com','connection': 'Keep-Alive','User-Agent':'Mozilla/5.0 (Linux; Android 11; V1981A Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36;sino-web.com'}
    data={
    'username':un,
    'password':pd,
    'pushId':'1104a897926bcb75f79',
    'schoolId':school
    }
    r=requests.post('https://swxykdsx.chuangnengkeji.com/api/login.json', data=data, headers=headers)
    if json.loads(r.text)['status']!=True:
        return json.loads(r.text)['msg']
    return json.loads(r.text)['result']['data']['token']

def download(url, cookie):
    header = {
        "Cookie": cookie,
        "referer":'https://swxykdsx.chuangnengkeji.com/'
        }
    print(header)
    r = requests.get(url, headers=header)
    with open('./code/'+username, 'wb') as f:
        f.write(r.content)

def base64_api(uname, pwd,  img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""

def setcookie(cookie,u,domain):
    token = {'domain': domain,'name': 'token', 'value': cookie}
    u.get('https://swxykdsx.chuangnengkeji.com/user/login')
    sleep(int(str(_time.time())[-3:])%3+3)
    u.add_cookie(token)

def optionCourse(cname):
    course_list = u.find_elements_by_xpath('/html/body/div[3]/div[2]/div[2]/div[1]/div[4]/div/div/div[2]/div[1]/a')
    sleep(int(str(_time.time())[-3:])%2+3)
    course_list[int(cname)-1].click()
    return "课程选择成功"

def getUrlLst():
    url = u.find_element_by_link_text("学习成绩").get_attribute('href')
    u.get(url)
    sleep(1)    
    print_log("已经学习 %s 个视频" % u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]').text)
    print_log("尚未学习 %s 个视频" % u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]').text) 
    
    lst=[]
    try:
        #未学完
        u.find_element_by_id('state').click()
        u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
        sleep(int(str(_time.time())[-3:])%2+3)
        u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
        sleep(int(str(_time.time())[-3:])%3+3)
        href_list = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
        lst.append(href_list[0].get_attribute('href'))
    except:
        print("无未学完视频。")
    try:
        #未学
        u.find_element_by_id('state').click()
        u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
        sleep(int(str(_time.time())[-3:])%2+3)
        u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
        sleep(int(str(_time.time())[-3:])%3+3)
        href_list = u.find_elements_by_xpath('//tr/td/a')
        for href in href_list:
            lst.append(href.get_attribute('href'))
        for _ in range(int(u.find_element_by_xpath('//div/div/span[3]').text)-1):
            u.find_element_by_xpath('/html/body/div[3]/div[2]/div/div[2]/div[5]/div/div[2]/a[5]').click()
            sleep(int(str(_time.time())[-3:])%5+3)
            href_list = u.find_elements_by_xpath('//tr/td/a')
            for href in href_list:
                lst.append(href.get_attribute('href'))
    except:
        print("无未学视频。")
        
    return lst
        
def play(lst):     
    for i in range(len(lst)):
        print("开始播放第%d个视频\n剩余%d个视频"%(i+1,len(lst)-i))
        u.get(lst[i])
        sleep(int(str(_time.time())[-3:])%7+3)
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[17]/canvas').click()#静音
        
        sleep(int(str(_time.time())[-3:])%3+1)
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]/canvas').click()#开始
        
        for _ in range(3):
            try:
                sleep(int(str(_time.time())[-3:])%5+1)
                yzm = u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/img[2]').get_attribute('src')
                
                cookieall=''
                cookies = u.get_cookies()
                for cookie in cookies:
                    cookieall+=cookie['name']+'='+cookie['value']+";"

                download(yzm,cookieall[:-1])
                result = base64_api(uname='yusheng615', pwd='1731249586', img=Image.open('./code/'+username))
                sleep(1)
                u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/input[2]').send_keys(result)
                sleep(1)
                u.find_element_by_link_text("开始播放").click()
            except:
                break

        print_log("开始时间是%s" % datetime.now())
        
        try:
            stime='00'
            ttime='00'
            while True:
                sleep(10)
                time=u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[8]').text
                print_log("播放中："+time)
                
                if ttime==str(time[:2]).strip() and stime==str(time[3:5]).strip():
                    print_log("视频暂停或完结")
                    break

                stime=str(time[3:5]).strip()
                ttime=str(time[:2]).strip()

                sleep(int(str(_time.time())[-3:])%50+300)#300
        except Exception as e:
            print_log("异常退出\n"+str(e))
            raise Exception()

def quit_c():
    u.quit()
    exit()

def print_log(string):
    print(string)
    string+='\n'
    with open("./log/"+username+'.log', 'a') as f:
        f.write(string)

def init(un,pd,ID):
    global username
    global password
    global pid
    username=un
    password =pd
    pid=ID

def run(un,pd,course,ID):
    while True:
        try:
            init(un,pd,ID)
            global cookie
            global u
            
            cookie=login(un,pd,39)
            u=webdriver_init()
            with open("./log/"+un+'.log', 'w') as f:
                f.write(cookie)
            print(cookie)
            setcookie(cookie,u,'.chuangnengkeji.com')
            u.get('https://swxykdsx.chuangnengkeji.com/user')
            sleep(3)
            
            ####检测初始密码修改框弹窗####
            try:
                u.find_element_by_xpath('//*[@id="layui-layer1"]/span[1]/a').click()
            except:
                sleep(1)
                
            try:
                sleep(2)
                try:
                    print("登录成功\n用户："+u.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[3]/div[1]/a/div[2]').text)
                except:
                    print("登录失败")
                    quit_c()
                    
                print_log(optionCourse(str(course)))
            except Exception as e:
                print_log("出错了\n"+str(e))
                quit_c()
            
            sleep(int(str(_time.time())[-3:])%3+1)
            play(getUrlLst())
            quit_c()
            break
        except Exception as e:
            quit_c()
            print(e)
    
if __name__=='__main__':
    inp=input('请输入学号:')
    run(inp,'a123456','1',inp)
